import ssl
import re
from flask import Flask, request, redirect, url_for
from flask_cors import CORS
from service.api.admin_api import admin
from service.api.message_api import message
from service.api.download import download
from service.api.upload_img import upload
from service.api.mail import mail, init_app
from service.api.class_api import category
from service.api.blog_api import blog
from get_config.index import upload_dir, html_dir, config
from service.log.index import log, create_http_logger
# from pprint import pprint

# __name__:将服务的基路径设置为当前文件的目录
# static_folder：设置静态文件夹的路径，以当前基路径为准
# static_url_path：是我们再url里输入地址用来指向静态文件的
app = Flask(__name__, static_folder=upload_dir, static_url_path='/img', template_folder=html_dir)
# 配置跨域
CORS(app, supports_credentials=True, origins=config["origins"])

# 获取到邮箱配置并循环添加至app.config中
for key in config["mail_config"]:
    app.config[key] = config["mail_config"][key]

app.register_blueprint(blueprint=admin, url_prefix='/api/admin')
app.register_blueprint(blueprint=upload, url_prefix='/api/upload')
app.register_blueprint(blueprint=download, url_prefix='/api/download')
app.register_blueprint(blueprint=message, url_prefix='/api/message')
app.register_blueprint(blueprint=mail, url_prefix='/api/mail')
app.register_blueprint(blueprint=category, url_prefix='/api/class')
app.register_blueprint(blueprint=blog, url_prefix='/api/blog')
app.register_blueprint(blueprint=log, url_prefix='/')

init_app(app)


@app.after_request
def log_response(response):
    # 只记录成功的响应（即200状态码）
    if response.status_code == 200 and request.method != "GET":
        # 你可以根据需要添加更多的日志信息，比如请求的URL、方法、耗时等
        http_logger_200 = create_http_logger(200)
        http_logger_200.info(f'200 OK: {request.method} {request.url}')
    return response


@app.errorhandler(404)
def handle_404(e):
    http_logger_404 = create_http_logger(404)
    http_logger_404.error(f'404 Not Found: {request.url}')
    return f'404 Not Found: {request.url}', 404


@app.errorhandler(500)
def handle_500(e):
    http_logger_500 = create_http_logger(500)
    http_logger_500.error(f'Internal Server Error: {e}')
    return 'Internal Server Error', 500




@app.route('/')
def detect_device():
    # 正则表达式用于匹配常见的移动设备User-Agent
    MOBILE_USER_AGENT_REGEX = re.compile(
        r'(?i)Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini'
    )
    user_agent = request.headers.get('User-Agent')
    if MOBILE_USER_AGENT_REGEX.search(user_agent):
        # 如果匹配到移动设备，重定向到手机端页面
        return redirect(url_for('mobile_page', _external=True, _scheme='https' if request.is_secure else 'http'))
    else:
        # 否则，重定向到PC端页面
        return redirect(url_for('desktop_page', _external=True, _scheme='https' if request.is_secure else 'http'))


# 假设的手机端页面路由（实际上应该是你的手机端前端页面的URL）
@app.route('/mobile')
def mobile_page():
    # 这里通常不会直接返回响应，而是应该重定向到你的手机端前端页面
    # 例如，如果你的手机端前端页面托管在另一个域或子域上，你应该重定向到那里
    return redirect('http://192.168.31.144:5500/index.html')  # 替换为你的手机端页面URL


# 假设的PC端页面路由（实际上应该是你的PC端前端页面的URL）
@app.route('/desktop')
def desktop_page():
    # 同上，这里应该重定向到你的PC端前端页面
    return redirect('http://localhost:8080/index')  # 替换为你的PC端页面URL


def run_app(debug=False):
    if debug:
        app.debug = debug
    if config["is_ssl"]:
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(config["crt"], config["key"])
        app.run(config["ssl_host"], config["port"], ssl_context=context)
    else:
        app.run(config["host"], config["port"])


if __name__ == '__main__':
    run_app()
